package org.jeecg.modules.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.mes.entity.MesTemplateWorkType;
import org.jeecg.modules.mes.mapper.MesTemplateWorkTypeMapper;
import org.jeecg.modules.mes.service.IMesTemplateWorkTypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: 生产计划模板工种配置
 * @Author: jeecg-boot
 * @Date: 2025-01-21
 * @Version: V1.0
 */
@Service
public class MesTemplateWorkTypeServiceImpl extends ServiceImpl<MesTemplateWorkTypeMapper, MesTemplateWorkType> implements IMesTemplateWorkTypeService {

    @Override
    public List<MesTemplateWorkType> getWorkTypesByTemplateId(String templateId) {
        QueryWrapper<MesTemplateWorkType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("template_id", templateId);
        queryWrapper.orderByAsc("sequence");
        return this.list(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteByTemplateId(String templateId) {
        QueryWrapper<MesTemplateWorkType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("template_id", templateId);
        return this.remove(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveTemplateWorkTypes(String templateId, List<MesTemplateWorkType> workTypes) {
        // 先删除原有的工种配置
        this.deleteByTemplateId(templateId);
        
        // 保存新的工种配置
        if (workTypes != null && !workTypes.isEmpty()) {
            for (MesTemplateWorkType workType : workTypes) {
                workType.setTemplateId(templateId);
                workType.setId(null); // 确保是新增
            }
            return this.saveBatch(workTypes);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean copyTemplateWorkTypes(String sourceTemplateId, String targetTemplateId) {
        // 获取源模板的工种配置
        List<MesTemplateWorkType> sourceWorkTypes = this.getWorkTypesByTemplateId(sourceTemplateId);
        
        if (sourceWorkTypes != null && !sourceWorkTypes.isEmpty()) {
            // 复制工种配置到目标模板
            for (MesTemplateWorkType workType : sourceWorkTypes) {
                workType.setId(null); // 清空ID，确保是新增
                workType.setTemplateId(targetTemplateId); // 设置新的模板ID
                workType.setCreateBy(null); // 清空创建信息，让系统自动填充
                workType.setCreateTime(null);
                workType.setUpdateBy(null);
                workType.setUpdateTime(null);
            }
            return this.saveBatch(sourceWorkTypes);
        }
        return true;
    }
}
